# -*- coding: utf-8 -*-
#!/usr/bin/env python

# Copyright (c) 2008 Carnegie Mellon University.
#
# You may modify and redistribute this file under the same terms as
# the CMU Sphinx system.  See
# http://cmusphinx.sourceforge.net/html/LICENSE for more information.

import gobject
#from gi.repository import GObject
import pygst
gobject.threads_init()
from gi.repository import Gst
from pocketsphinx import Lattice, Decoder
from TurtleArt.tautils import (find_top_block)
from TurtleArt.taturtle import Turtle

def trash(tw):
	for b in tw.just_blocks():
		if b.type != 'trash':
		    if b.name == 'butia-listens':  # Don't trash start block
		        b1 = b.connections[-1]
		        if b1 is not None:
		            b.connections[-1] = None
		            b1.connections[0] = None
		            tw._put_in_trash(b1)
		    else:
		        tw._put_in_trash(find_top_block(b))


class EscucharApp(object):
    """GStreamer/PocketSphinx Escuchar Application"""
    def __init__(self,tw):
        """Initialize a DemoApp object"""
        self.init_gst()
	self.tw = tw
	self.start = False
 
    def init_gst(self):
        """Initialize the speech components"""
        self.pipeline = gst.parse_launch('gconfaudiosrc ! audioconvert ! audioresample '
                                         + '! vader name=vad auto-threshold=true '
                                         + '! pocketsphinx name=asr ! fakesink')
        asr = self.pipeline.get_by_name('asr')
        asr.connect('partial_result', self.asr_partial_result)
        asr.connect('result', self.asr_result)
	asr.set_property('fsg', "/asr/lm/butia-listens.fsg")
	asr.set_property('dict', "/asr/hmm/butia-listens.dic")
	asr.set_property('hmm', "/asr/hmm/voxforge-es-0.1.1/model_parameters/voxforge_es_sphinx.cd_cont_1500")
        asr.set_property('configured', True)
        bus = self.pipeline.get_bus()
        bus.add_signal_watch()
        bus.connect('message::application', self.application_message)
        self.pipeline.set_state(gst.STATE_PLAYING)

    def asr_partial_result(self, asr, text, uttid):
        """Forward partial result signals on the bus to the main thread."""
        struct = gst.Structure('partial_result')
        struct.set_value('hyp', text)
        struct.set_value('uttid', uttid)
        asr.post_message(gst.message_new_application(asr, struct))

    def asr_result(self, asr, text, uttid):
        """Forward result signals on the bus to the main thread."""
        struct = gst.Structure('result')
        struct.set_value('hyp', text)
        struct.set_value('uttid', uttid)
        asr.post_message(gst.message_new_application(asr, struct))

    def application_message(self, bus, msg):
        """Receive application messages from the bus."""
        msgtype = msg.structure.get_name()
        if msgtype == 'partial_result':
            self.partial_result(msg.structure['hyp'], msg.structure['uttid'])
        elif msgtype == 'result':
            self.final_result(msg.structure['hyp'], msg.structure['uttid'])

    def partial_result(self, hyp, uttid):
        """Delete any previous selection, insert text and select it."""
        # All this stuff appears as one single action     

    def final_result(self, hyp, uttid):
        """Insert the final result."""
        # All this stuff appears as one single action 
	orden = hyp.lower()
	if orden == "ejecutar":
		self.pipeline.set_state(gst.STATE_PAUSED)
	if orden == "atras butia":
		orden = "atrás Butiá"
		self.tw.prim_load_block(orden)
	elif orden == "adelante butia":
		orden = "adelante Butiá"
		self.tw.prim_load_block(orden)
	elif orden == "derecha butia":
		orden = "derecha Butiá"
		self.tw.prim_load_block(orden)
	elif orden == "izquierda butia":
		orden = "izquierda Butiá"
		self.tw.prim_load_block(orden)
	elif orden == "detener butia":
		orden = "detener Butiá"
		self.tw.prim_load_block(orden)
	elif orden == "limpiar" :
		self.start = False
		trash(self.tw)
		Turtle.set_pen_state(self.tw.turtles.get_active_turtle(),False)
		Turtle.set_xy(self.tw.turtles.get_active_turtle(),0.0,0.0)
		Turtle.set_pen_state(self.tw.turtles.get_active_turtle(),True)
	elif orden == "ejecutar":
		self.tw.lc.trace = 1
		self.tw.step_time = 3
		self.tw.run_button(self.tw.step_time, running_from_button_push=True)
		self.tw.prim_load_block("esperar",1)
	elif ((orden == "empezar") and (not self.start)):
		self.start = True
		orden = "empezar"
		self.tw.prim_load_block(orden)
	elif orden == "esperar uno":
		self.tw.prim_load_block("esperar",1)
	elif orden == "esperar dos":
		self.tw.prim_load_block("esperar",2)
	elif orden == "esperar tres":
		self.tw.prim_load_block("esperar",3)
	elif orden == "esperar cuatro":
		self.tw.prim_load_block("esperar",4)
	elif orden == "esperar cinco":
		self.tw.prim_load_block("esperar",5)
	elif orden == "esperar seis":
		self.tw.prim_load_block("esperar",6)
	elif orden == "esperar siete":
		self.tw.prim_load_block("esperar",7)
	elif orden == "esperar ocho":
		self.tw.prim_load_block("esperar",8)
	elif orden == "esperar nueve":
		self.tw.prim_load_block("esperar",9)
	elif orden == "esperar diez":
		self.tw.prim_load_block("esperar",10)
	
	

